import cgi

from db_module import *
from common import *
from google.appengine.ext import webapp

class Guestbook(webapp.RequestHandler):
  def get(self):
        check_user(self)
        self.response.out.write('<html><body><a href="/">Back to home</a><br />')
        greetings = db.GqlQuery("SELECT * FROM Greeting ORDER BY date DESC LIMIT 10")
        for greeting in greetings:
          if greeting.author:
            self.response.out.write('<b>%s</b> wrote:' % Register.gql("where username = :1",  greeting.author).get().nickname)
          else:
            self.response.out.write('An anonymous person wrote:')
          self.response.out.write('<blockquote>%s</blockquote>' %
                                  cgi.escape(greeting.content))
    
        # Write the submission form and the footer of the page
        self.response.out.write("""
              <form action="/sign" method="post">
                <div><textarea name="content" rows="3" cols="60"></textarea></div>
                <div><input type="submit" name="submit" value="Sign Guestbook"></div>""")
        if users.is_current_user_admin():
            self.response.out.write("""
                <div><input type="submit" name="clear" value="Clear Guestbook"></div>""")
        self.response.out.write("""
              </form>
            </body>
      </html>""")
    
    
  def post(self):
    if self.request.get('clear'):
        self.response.headers['Content-Type'] = 'text/plain'
        try:
            while True:
                q = db.GqlQuery("SELECT __key__ FROM Greeting")
                assert q.count()
                db.delete(q.fetch(200))
                time.sleep(0.5)
        except Exception, e:
            self.response.out.write(repr(e)+'\n')
            pass
        self.redirect('/sign')
    else:
        greeting = Greeting()
        greeting.author = get_username()
        greeting.content = self.request.get('content')
        greeting.put()
        self.redirect('/sign')